<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ImageUploader from './components/ImageUploader.vue'
import ImageGrid from './components/ImageGrid.vue'
import ImagePreview from './components/ImagePreview.vue'
import LoginPage from './components/LoginPage.vue'

const router = useRouter()
const isLoggedIn = ref(false)

// 定义响应式数据
const images = ref([])
const previewImageIndex = ref(0) // 当前预览图片的索引
const showPreview = ref(false)

// 获取所有图片
const fetchImages = async () => {
  try {
    const response = await fetch('https://ssfcpcwrzqns.sealoshzh.site/api/images/get');
    const result = await response.json();
    if (result.code === 200) {
      images.value = result.data.map(image => ({
        _id: image._id,
        name: image.name,
        url: image.url,
        description: image.description,
      }));
    } else {
      console.error(result.message);
    }
  } catch (error) {
    console.error('获取图片失败:', error);
  }
}

// 检查登录状态
const checkLoginStatus = () => {
  const status = localStorage.getItem('isLoggedIn')
  isLoggedIn.value = status === 'true'
}

// 在组件挂载时获取图片和检查登录状态
onMounted(() => {
  fetchImages();
  checkLoginStatus();
});

// 处理图片上传
const handleUpload = async (newImages) => {
  try {
    const formData = new FormData();
    
    // 将每个文件对象添加到 FormData
    newImages.forEach((file, index) => {
      formData.append('images', file); // 使用 'images' 作为字段名
    });

    const response = await fetch('https://ssfcpcwrzqns.sealoshzh.site/api/images/add', {
      method: 'POST',
      body: formData, // 发送 FormData
    });

    // 检查响应状态
    if (!response.ok) {
      const errorText = await response.text(); // 获取错误文本
      console.error('上传图片失败:', errorText);
      return;
    }

    const result = await response.json();
    if (result.code === 201) {
      images.value.push(...result.data); // 添加新上传的图片
    } else {
      console.error(result.message);
    }
  } catch (error) {
    console.error('上传图片失败:', error);
  }
}

// 处理图片删除
const handleDelete = (index) => {
  const image = images.value[index];
  const filename = image.name || image.url.split('/').pop(); // 从 url 中提取文件名
  deleteImage(filename, index);
}

// 删除图片
const deleteImage = async (filename, index) => {
  try {
    const response = await fetch('https://ssfcpcwrzqns.sealoshzh.site/api/images/del', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ filename: filename }), // 发送包含 filename 的请求体
    });

    // 检查响应状态
    if (!response.ok) {
      const errorText = await response.text(); // 获取错误文本
      console.error('删除图片失败:', errorText);
      return;
    }

    const result = await response.json();
    if (result.code === 200) {
      window.location.reload(); // 删除成功后刷新页面
    } else {
      console.error(result.message);
    }
  } catch (error) {
    console.error('删除图片失败:', error);
  }
}

const handleImageClick = (image, index) => {
  previewImageIndex.value = index
  showPreview.value = true
}

const handleChangeIndex = (newIndex) => {
  previewImageIndex.value = newIndex
}

// 处理预览界面的删除
const handlePreviewDelete = (index) => {
  const image = images.value[index];
  const filename = image.name || image.url.split('/').pop(); // 从 url 中提取文件名
  deleteImage(filename, index);
  showPreview.value = false; // 关闭预览界面
}
</script>

<template>
  <div class="app-container">
    <template v-if="isLoggedIn">
      <header class="app-header">
        <h1>图片画廊</h1>
        <p class="subtitle">分享你的精彩瞬间</p>
      </header>
      
      <main class="main-content">
        <ImageUploader @upload-images="handleUpload" />
        <ImageGrid
          :images="images"
          @delete-image="handleDelete"
          @image-click="handleImageClick"
        />
        <ImagePreview
          :show="showPreview"
          :images="images"
          :current-index="previewImageIndex"
          @close="showPreview = false"
          @change-index="handleChangeIndex"
          @delete-image="handlePreviewDelete"
        />
      </main>
    </template>
    <template v-else>
      <LoginPage />
    </template>
  </div>
</template>

<style>
@import './assets/theme.css';
@import 'animate.css';

/* 移除全局最小宽度 */
html, body {
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}

.app-container {
  min-height: 100vh;
  width: 100%; /* 改为100%宽度 */
  display: flex;
  flex-direction: column;
  background: var(--background-color);
  max-width: 1920px;
  margin: 0 auto;
  padding: 0;
  height: 100vh;
  overflow: hidden;
}

.app-header {
  padding: 25px 20px;
  background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
  color: white;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
}

.app-header h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: -0.5px;
}

.subtitle {
  margin: 6px 0 0;
  font-size: 15px;
  opacity: 0.9;
}

.main-content {
  flex: 1;
  width: 100%;
  max-width: 1800px;
  margin: 100px auto 0;
  padding: 20px;
  box-sizing: border-box;
  overflow-y: auto;
  height: calc(100vh - 100px);
}

/* 桌面端断点 */
@media (min-width: 1440px) {
  .app-container {
    min-width: 1440px;
  }
  
  .app-header {
    min-width: 1440px;
  }
  
  .main-content {
    min-width: 1440px;
  }
}

/* 平板端断点 */
@media (max-width: 1439px) {
  .app-container {
    width: 100%;
    min-width: unset;
  }
  
  .app-header {
    width: 100%;
    min-width: unset;
  }
  
  .main-content {
    width: 100%;
    min-width: unset;
    padding: 15px;
  }
}

/* 移动端断点 */
@media (max-width: 768px) {
  .app-header {
    padding: 20px 15px;
  }
  
  .app-header h1 {
    font-size: 22px;
  }
  
  .main-content {
    margin-top: 80px;
    height: calc(100vh - 80px);
    padding: 15px;
  }
}

/* 平板横屏模式 */
@media (orientation: landscape) and (max-width: 1200px) {
  .app-container {
    min-width: 100%; /* 横屏时适配整个屏幕 */
    max-width: none; /* 移除最大宽度限制 */
    height: 100%; /* 设置高度为100%,充满屏幕 */
    display: flex;
    flex-direction: column;
  }

  .app-header {
    padding: 20px 40px; /* 增加左右内边距 */
  }

  .main-content {
    max-width: none; /* 移除最大宽度限制 */
    margin: 100px 0 0; /* 移除上下边距 */
    padding: 20px 40px; /* 增加左右内边距 */
    height: calc(100% - 140px); /* 调整高度,减去标题的高度 */
    overflow-y: auto;
  }
}
</style>
